# 录音保存
import wave
from config import *
import time

#保存录音到本地
def save_recod_local(start_time,RECORD_SECONDS):
    while True:
        try:
            p = pyaudio.PyAudio()
            stream = p.open(format=FORMAT,
                            channels=CHANNELS,
                            rate=RATE,
                            input=True,
                            frames_per_buffer=CHUNK,
                            input_device_index=device_id,  # 指定设备 index值
                            )
            # 录制音频
            frames = []
            time1 = str(time.strftime("%Y%m%d-%H%M%S", time.localtime()))
            WAVE_OUTPUT_FILENAME = f"data/recod_{start_time}/output" + time1 + ".mp3"

            for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
                data = stream.read(CHUNK)
                frames.append(data)

            # 关闭音频流
            #stream.stop_stream()
            #stream.close()
            #p.terminate()

            # 保存音频文件
            wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
            wf.setnchannels(CHANNELS)
            wf.setsampwidth(p.get_sample_size(FORMAT))
            wf.setframerate(RATE)
            wf.writeframes(b''.join(frames))
            wf.close()
            print(f"\033[32m {time1} 录音完成 \033[0m")
        except Exception as e:
            print('recod err',e)
            with open("logs/err.log", "a") as fil1:  # 相对路径打开文件
                fil1.write(time1+'  err:'+str(e)+'\n')
            time.sleep(60)

#保存录音到oss
def save_recod_oss(time,RECORD_SECONDS):
    pass

if __name__ == '__main__':
    pass